package cn.xyt.util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.StringUtils;

import cn.tom.kit.io.FileUtil;


public class HttpUtil1 {
	public static final Logger LOG = LoggerFactory.getLogger(HttpUtil1.class);

	public static String sendPostWithJson(String url, String content, int timeout) {
		LOG.debug("ready for send post[url={},content={}]", url, content);
		String responseContent = null;
		try {
			URI uri = new URI(url);
			SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
			schr.setConnectTimeout(timeout);
			schr.setReadTimeout(timeout);
			ClientHttpRequest request = schr.createRequest(uri, HttpMethod.POST);
			request.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
			if (StringUtils.hasLength(content)) {
				request.getBody().write(content.getBytes("UTF-8"));
			}
			ClientHttpResponse resp = request.execute();
			String responseBody = FileUtil.streamToStr(resp.getBody(), "UTF-8");
			int statusCode = resp.getRawStatusCode();
			LOG.debug("send post result responseStatus={},responseContent={}", statusCode, responseBody);
			if (statusCode!=200) {
				LOG.error("http post faild[error=response statusCode[{}] not 200,url={},params={}]", new Object[] { statusCode, url, content });

				return responseContent;
			}
			responseContent = responseBody;
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			LOG.error("http post faild,url={},params={},error={}", new Object[] { url, content, e.getMessage() });
		}
		LOG.debug("post success[url={},request={},response={}]", new Object[] { url, content, responseContent });
		LOG.info("send info to server success[request={}, response={}]", content, responseContent);
		return responseContent;
	}
}
